package com.chao.search;

/**
 * @author : Rookie
 * @description : 二分查找
 * @date : 2023/7/3
 */
public class BinarySearch {

    public static void main(String[] args) {
        int[] arr = new int[] {0,2,5,6,8,13,35,41};
        int target = 13;
        int result = search(arr, target);
        System.out.println(result);
    }

    private static int search(int []arr,int target) {
//        return cycleImpl(arr, target);
        return recursionImpl(arr,target,0,arr.length - 1);
    }

    private static int recursionImpl(int []arr,int target,int left,int right) {
        if (left > right) {
            return -1;
        }
        int mid = (left + right) / 2;
        if (arr[mid] > target) {
            right = mid - 1;
        } else if (arr[mid] < target) {
            left = mid + 1;
        } else {
            return mid;
        }
        return recursionImpl(arr, target, left, right);
    }

    private static int cycleImpl(int []arr,int target) {
        int left = 0,right = arr.length - 1,index = -1;
        while (left < right) {
            int mid = (left + right) / 2;
            if (arr[mid] > target) {
                right = mid - 1;
            } else if (arr[mid] < target) {
                left = mid + 1;
            } else {
                index = mid;
                break;
            }
        }
        return index;
    }
}
